package com.baymax.utils;

import cn.hutool.core.collection.CollUtil;
import com.baymax.security.properties.SecurityProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * Redis缓存工具类
 *
 * @Author: baymax
 * @CreateTime: 2023/3/29 16:54
 * @Version: 1.0
 */
@Component
@Slf4j
public class RedisUtil {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private SecurityProperties securityProperties;

    public Object get(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    public Long getExpireTime(String key) {
        return redisTemplate.opsForValue().getOperations().getExpire(key);
    }

    public void set(String key, Object value) {
        try {
            redisTemplate.opsForValue().set(key, value);
        } catch (Exception e) {
            throw new RuntimeException("Redis操作异常");
        }
    }

    public void set(String key, Object value, long timeout, TimeUnit unit) {
        try {
            redisTemplate.opsForValue().set(key, value, timeout, unit);
        } catch (Exception e) {
            throw new RuntimeException("Redis操作异常");
        }
    }

    public void deletePrefixKey(String prefixKey) {
        try {
            Set<String> keys = redisTemplate.keys(prefixKey + "*");
            if (CollUtil.isNotEmpty(keys)) {
                redisTemplate.delete(keys);
            }
        } catch (Exception e) {
            throw new RuntimeException("Redis操作异常");
        }
    }
}
